from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse, request
from django.shortcuts import render

from newsm.models import News,Category,Comment


# 获取所有新闻
@login_required(login_url='/users/login')
def news(request):
   news = News.objects.all()
   # 转换为字典
   # res=[model_to_dict(item) for item in news]
   # safe: True(字典)  False(列表)
   # return JsonResponse(res,safe=False,json_dumps_params={'ensure_ascii':False})
   # 获取? key=val 的参数
   # 如果currentPage获取不到，就默认为1
   currentPage=request.GET.get('currentPage',1)
   # 分页器
   paginator = Paginator(news,2) #每页显示2条
   page = paginator.page(currentPage) #对应页码的page对象
   return render(request,'news_list.html',{'page':page})

@login_required(login_url='/users/login')
def detail(request,id):
    new=News.objects.get(id=id)
    comments =new.comments.all().order_by('-createDate') #降序排序
    return render(request,'news_detail.html',{'new':new,'comments':comments})

@login_required(login_url='/users/login')
def category(request):
    cat=Category.objects.all()
    return render(request,'news_category.html',{'cat':cat})

def comment(request,newId):
    new = News.objects.get(id=newId)
    user = request.user
    content = request.POST.get('content')
    createDate = datetime.now().strftime("%Y年%m月%d日 %H:%M")
    comment = Comment.objects.create(new=new,user=user,content=content,createDate=createDate)
    dic = model_to_dict(comment)
    dic['createDate']=createDate
    if  comment:
        return JsonResponse({'code':200,'msg':'评论成功','data':dic},safe=True)
    return JsonResponse({'code':400,'msg':'评论失败'},safe=True)


